/*
 *  (C) Copyright 2008 Insula Tecnologia da Informacao Ltda.
 * 
 *  This file is part of Vulcano.
 *
 *  Vulcano is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Vulcano is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Vulcano.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.openinsula.vulcano.flex;

import javax.annotation.PostConstruct;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.openinsula.vulcano.flex.example.persistence.Department;
import org.openinsula.vulcano.flex.example.persistence.EntityFactory;
import org.openinsula.vulcano.flex.example.persistence.Person;
import org.openinsula.vulcano.flex.example.persistence.Role;
import org.openinsula.vulcano.flex.example.persistence.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

@ContextConfiguration(locations = { "/test-context.xml", "classpath*:META-INF/*-context.xml" })
public abstract class AbstractFlexHibernateTestCase extends AbstractTransactionalJUnit4SpringContextTests {

	@Autowired
	private SessionFactory sf;

	protected final Session getSession() {
		try {
			return sf.getCurrentSession();
		}
		catch (HibernateException e) {
			return sf.openSession();
		}
	}

	protected void populate() {
		Session session = getSession();
		session.beginTransaction();

		Department department = EntityFactory.createDepartment("IT");
		session.save(department);

		Person person = EntityFactory.createPerson("John Doe", department);
		session.save(person);

		Role role1 = EntityFactory.createRole("ADMIN");
		session.save(role1);

		Role role2 = EntityFactory.createRole("USER");
		session.save(role2);

		User user = EntityFactory.createUser(person, "john_doe", "123");
		user.getRoles().add(role1);
		user.getRoles().add(role2);
		session.save(user);

		session.getTransaction().commit();
		session.close();
	}

	@PostConstruct
	public final void prepare() {
		super.deleteFromTables("User_Role", "User", "Role", "Person", "Department");
		populate();
	}

}